package com.github.catvod.spider;

import com.github.catvod.bean.Class;
import com.github.catvod.bean.Result;
import com.github.catvod.bean.Vod;
import com.github.catvod.crawler.Spider;
import com.github.catvod.net.OkHttp;
import com.github.catvod.utils.Util;

import org.json.JSONObject;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author: fs
 * @date: 2025/1/16 15:06
 * @description: 麻豆爬虫
 */
public class MaDou extends Spider {
    private String sistUrl="https://madou.fit/";
    private String categoryUrl=sistUrl+"index.php/vod/type/id/";
    private String searchUrl=sistUrl+"index.php/vod/search/page/";

    private Map<String, String> getHeader() {
        Map<String, String> header = new HashMap<>();
        header.put("User-Agent", Util.CHROME);
        header.put("accept-language", "zh-CN,zh;q=0.9");
        header.put("sec-fetch-mode", "cors");
        return header;
    }

    private List<Vod> parseVocd(Document doc) {
        List<Vod> videos = new ArrayList<>();
        Elements vodList = doc.select("ul.stui-vodlist");
        for (Element element : vodList) {
            Elements item_list = element.select("li");
            for (Element item : item_list) {
                String title = item.select(".title").text();
                String pic = item.select("a.stui-vodlist__thumb").attr("data-original");
                String url = item.select("a.stui-vodlist__thumb").attr("href");
                String year = item.select("p.sub").text();
                String remark="";
                // 进行获取"播放后的字符"
                if (year.contains("播放")){
                    year = year.split("播放")[1];
                    remark=year.split("播放")[0];
                }
                Vod vod = new Vod();
                vod.setVodId(url);
                vod.setVodName(title);
                vod.setVodPic(pic);
                vod.setVodYear(year);
                vod.setVodRemarks(remark);
                videos.add(vod);
            }
        }
        return videos;
    }
    @Override
    public String homeContent(boolean filter) throws Exception {
        Document doc = Jsoup.parse(OkHttp.string(sistUrl, getHeader()));
        List<Vod> videos=parseVocd(doc);
        List<String> typeName = Arrays.asList("首页", "麻豆", "日本", "探花", "华语", "欧美");
        List<String> typeId = Arrays.asList("0", "1", "2", "3", "4", "5");
        List<Class> classes = new ArrayList<>();
        for (String id : typeId) {
            classes.add(new Class(id, typeName.get(typeId.indexOf(id))));
        }
        return Result.string(classes, videos);
    }

    @Override
    public String categoryContent(String tid, String pg, boolean filter, HashMap<String, String> extend) throws Exception {
        if (tid.equals("0")) {
            // 获取首页数据
            Document doc = Jsoup.parse(OkHttp.string(sistUrl, getHeader()));
            List<Vod> videos=parseVocd(doc);
            return Result.string(videos);
        }
        Document doc = Jsoup.parse(OkHttp.string(categoryUrl + tid +"/page/"+pg+ ".html", getHeader()));
        // 获取总页数
        String page_count = doc.select("span.num").text().split("/")[1];
        List<Vod> videos=parseVocd(doc);
        return Result.string(Integer.parseInt(pg),Integer.parseInt(page_count),30,videos.size(),videos);
    }

    @Override
    public String detailContent(List<String> ids) throws Exception {
        if (sistUrl.endsWith("/")){
            sistUrl=sistUrl.substring(0,sistUrl.length()-1);
        }
        String detailUrl=sistUrl+ids.get(0);
        Document doc =  Jsoup.parse(OkHttp.string(detailUrl, getHeader()));
        String title = doc.select("h3.title").text();
        String remark = doc.select(".mac_hits .hits").text();
        String regex="<script type=\"text/javascript\">var player_aaaa=(.*)</script>";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(doc.html());
        String strObject = matcher.find() ? matcher.group(1) : "";
        JSONObject jsonObject = new JSONObject(strObject);
        String playUrl =jsonObject.get("url").toString();
        // 发送请求获取播放链接
//        String playUrl = OkHttp.string(m3u8_url, getHeader());
        // 进行获取最后一行数据
//        String[] lines = playUrl.split("\n");
//        playUrl = lines[lines.length - 1].trim();
        Vod vod = new Vod();
        vod.setVodId(ids.get(0));
        vod.setVodName(title);
        vod.setVodPic("");
        vod.setVodRemarks(remark);
        vod.setVodPlayFrom("m3u8");
        vod.setVodPlayUrl("播放$"+playUrl);
        return Result.string(vod);
    }

    @Override
    public String playerContent(String flag, String id, List<String> vipFlags) throws Exception {
        return Result.get().url(id).header(getHeader()).string();
    }

    @Override
    public String searchContent(String key, boolean quick) throws Exception {
        String url=searchUrl+"1/wd/"+key+".html";
        Document doc = Jsoup.parse(OkHttp.string(url, getHeader()));
        List<Vod> videos=parseVocd(doc);
        return Result.string(videos);
    }
}
